#!/usr/bin/env python
import sys
import os

# TODO -- this should eventually be redone with func or puppet
hostsloc='/root/nagios/hosts-lists'
location='/root/nagios/nrpe-distribution-jams'

# TODO -- someday these should be pulled from nagiosconfig.py
groups = ['32b_hosts', '64b_hosts']

def load_hosts(filename):
    return [h.strip() for h in open(filename).readlines()]

def format_host_list(hlist):
    PREFIX = "    "
    SEP = ", "
    lines = []
    i = 0
    for h in hlist:
        if len(lines) ==  i:
            lines.append(PREFIX + h)
            continue
        if len(lines[i] + SEP + h) > 80-len(SEP):
            lines[i] += SEP
            i = i + 1
            lines.append(PREFIX + h)
            continue
        lines[i] += SEP + h

    return "\n".join(lines)

def determine_host_list():
    master_host_lists = {}
    master_host_lists['all_hosts'] = [
        l.strip() for l in 
        os.popen('/root/nagios/localutils/get-list-of-unix-hosts.py').readlines()
    ]
    biglist = master_host_lists['all_hosts']
    
    # TODO -- eventually do this with optparse
    host_list = sys.argv[1:]
    for group in groups:
        if group in host_list:
            print "Using host-list: '%s'" % group
            i = host_list.index(group)
            host_list[i:i+1] = master_host_lists[group]

    # The default:
    if len(host_list) == 0:
        host_list = master_host_lists['all_hosts']

    # Get rid of any duplicates
    noDupes = [] 
    [noDupes.append(i) for i in host_list if not noDupes.count(i)] 
    for host in noDupes:
        if not host in biglist:
            raise ValueError, 'Host "%s" is not in my config as a valid host.' \
                    % host

        

    return noDupes
def run_cmd(cmd):
    cmd = '%s/%s' % (location, cmd)
    print "running cmd:", cmd
    lines = os.popen(cmd)
    for line in lines:
        print "  ", line,
    print "done with cmd:", cmd

if __name__ == '__main__':
    if '-h' in sys.argv[1:]:
        print """
Usage:
    get-and-distribute-nrpe-jams [-h]
    get-and-distribute-nrpe-jams [-h] host1 host2 ...
    get-and-distribute-nrpe-jams [-h] hostgroup1 hostgroup2 ...


    With no parameters, get-and-distribute-nrpe-jams will use every host
    it knows of as a target.
    
    Hosts can be listed on the command line.  Only valid hosts are accepted.
    
    Possible hostgroups are:
        %s
        """ % ", ".join(groups)
        sys.exit(0)

    host_list = determine_host_list()
    print "Going to use the following %i hosts:" % len(host_list)
    print format_host_list(host_list)
    resp = raw_input("Distribute to the above %i hosts [y/N]:" % len(host_list))
    if not resp.strip() in ['Y', 'Yes', 'YES', 'yes', 'y']:
        print "Aborting."
        sys.exit(0)
    run_cmd('nrpe-jams-setup.sh')
    for host in host_list:
        run_cmd('nrpe-jams-distribute-to-host.sh %s' % host)
    run_cmd('nrpe-jams-cleanup.sh')
